using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
public partial class asp_pages_CheckOut : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Item> list = Session["cart"] as List<Item>;
            rptCheckOut.DataSource = list;
            rptCheckOut.DataBind();
            lblOrderDate.Text = DateTime.Now.ToString("MMM dd, yyyy - hh:mm:ss tt");
            decimal total = 0;
            foreach (Item item in list) { total += item.Amount; }
            lblTotal.Text = total.ToString();
        }
    }
    protected void btnFinish_Click(object sender, EventArgs e)
    {
        if (chkConfirm.Checked == false)
        {
            lblMessage.Text = "You must agree to buy these items. Please check the below checkbox.";
            return;
        }
        Validate();
        if (!IsValid) return;
        Customer person = new Customer();
        Order order = new Order();
        PersonDAO daoPerson = new PersonDAO();
        CustomerDAO daoCustomer = new CustomerDAO();
        OrderDAO daoOrder = new OrderDAO();
        person.Name = txtCustomerName.Text;
        person.Address = txtAddress.Text;
        person.Phone = txtPhone.Text;
        person.Email = txtEmail.Text;
        person.CreditCard = txtCreditCard.Text;
        if (daoPerson.Insert(person) > 0)
        {
            order.OrderDate = DateTime.Now;
            order.Customer = person;
            order.ReceiverAddress = txtReceiverAddress.Text;
            if (daoCustomer.InsertCustomer(person) > 0)
                if (daoOrder.InsertOrder(order) > 0)
                {
                    List<Item> list = Session["cart"] as List<Item>;
                    OrderDetailsDAO daoOD = new OrderDetailsDAO();
                    bool rs = true;
                    foreach (Item item in list)
                    {
                        item.OrderID = order.OrderID;
                        if (daoOD.InsertOrderDetails(item) <= 0) { rs = false; break; }

                    }
                    Response.Redirect("checkoutCompleted.aspx");
                }
                else lblMessage.Text = "Sorry. Some error has ocurred. Please come back later.";
        }
    }
}
